package tom_io_nio.aio;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AioServer {

    private int port ;

    public static void main(String[] args){
        new AioServer(8080);
    }

    //注册端口
    public AioServer(int port){
        this.port = port;
        listener();
    }

    //监听方法
    private void listener(){

        try{
            //线程缓冲池，为了体现异步
            ExecutorService executorService = Executors.newCachedThreadPool();
            //给线程池初始化一个线程
            AsynchronousChannelGroup thredGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService,1);
            //asyncChronous异步
            //nio serverSockerChannel
            //Bio ServerSocket 有那么一点点像
            //和nio一样，先打开通道
            final AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open(thredGroup);
            //绑定
            serverSocketChannel.bind(new InetSocketAddress(this.port));
            System.out.println("服务端启动，监听端口：" + this.port);

            final Map<String,Integer> count = new ConcurrentHashMap<>();
            count.put("count",0);
            //开始等待客户端连接

            //实现一个ComletionHandler的接口，匿名的实现类
            serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

                final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

                @Override
                //实现IO操作完成的方法
                public void completed(AsynchronousSocketChannel result, Object attachment) {
                    count.put("count",count.get("count") + 1);

                    System.out.println(count.get("count"));
                    //只要拿数据
                    try{
                        buffer.clear();
                        result.read(buffer).get();
                        buffer.flip();
                        result.write(buffer);
                        buffer.flip();
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        try{
                            result.close();
                            serverSocketChannel.accept(null,this);
                        }catch (Exception e){
                            System.out.println(e.toString());
                        }
                    }
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.out.println("IO操作是失败: " + exc);
                }
            });

            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException ex) {
                System.out.println(ex);
            }
        }catch (IOException e){
            e.printStackTrace();
        }


    }
}
